<template>
  <div class="category-filter" ref="filterContainer">
    <!-- 0级 - 固定横向排列 -->
    <div class="level-0-container">
      <div 
        v-for="item in level0Data" 
        :key="item.id" 
        class="level-0-item"
        :class="{ active: activeIds[0] === item.id }"
        @click.stop="handleLevelClick(item, 0)"
        ref="level0Items"
      >
        {{ item.standardName }}
      </div>
    </div>

    <!-- 1-3级容器 - 固定在当前选中的0级下方，靠左，宽度与最外层同宽 -->
    <div 
      v-if="activeIds[0] && (level1Data.length > 0 || level2Data.length > 0 || level3Data.length > 0)"
      class="sub-levels-container"
      :style="subLevelPosition"
      @click.stop
    >
      <!-- 1级 -->
      <div v-if="level1Data.length > 0" class="level-1-container">
        <div
          v-for="item in level1Data"
          :key="item.id"
          class="level-1-item"
          :class="{ active: activeIds[1] === item.id }"
          @click.stop="handleLevelClick(item, 1)"
        >
          {{ item.standardName }}
        </div>
      </div>

      <!-- 2级 -->
      <div v-if="level2Data.length > 0" class="level-2-container">
        <div
          v-for="item in level2Data"
          :key="item.id"
          class="level-2-item"
          :class="{ active: activeIds[2] === item.id }"
          @click.stop="handleLevelClick(item, 2)"
        >
          {{ item.standardName }}
        </div>
      </div>

      <!-- 3级 -->
      <div v-if="level3Data.length > 0" class="level-3-container">
        <div
          v-for="item in level3Data"
          :key="item.id"
          class="level-3-item"
          :class="{ active: activeIds[3] === item.id }"
          @click.stop="handleLevelClick(item, 3)"
        >
          {{ item.standardName }}
        </div>
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ref, computed, onMounted, onUnmounted, nextTick } from "vue";

interface CategoryItem {
  id: string;
  standardName: string;
  pid: string;
  children?: CategoryItem[];
}

const props = defineProps<{
  data: CategoryItem[];
}>();

const emit = defineEmits<{
  (event: "update-selection", payload: { ids: string[] }): void;
}>();

// 当前选中的各级ID [0级, 1级, 2级, 3级]
const activeIds = ref<string[]>([]);
const level0Items = ref<HTMLElement[]>([]);
const subLevelPosition = ref({ left: '0', top: '0', width: '100%' });
const filterContainer = ref<HTMLElement | null>(null);

// 获取各级数据
const level0Data = computed(() => props.data);
const level1Data = computed(() => 
  activeIds.value[0] 
    ? props.data.find(item => item.id === activeIds.value[0])?.children || []
    : []
);
const level2Data = computed(() => 
  activeIds.value[1] 
    ? level1Data.value.find(item => item.id === activeIds.value[1])?.children || []
    : []
);
const level3Data = computed(() => 
  activeIds.value[2] 
    ? level2Data.value.find(item => item.id === activeIds.value[2])?.children || []
    : []
);

// 处理点击事件



const handleLevelClick = async (item: CategoryItem, level: number) => {
  // 更新当前级别的选中ID
  activeIds.value[level] = item.id;

  // 清空更高级别的选中状态
  for (let i = level + 1; i < 4; i++) {
    activeIds.value[i] = "";
  }

  // 更新子级容器位置
  if (level === 0) {
    await nextTick();
    updateSubLevelPosition();
  }

  // 获取最末级的选中ID
  const lastSelectedId = activeIds.value
    .slice() // 创建副本以避免直接操作原数组
    .reverse() // 反转数组以从后往前查找
    .find(id => id !== ""); // 找到第一个非空ID

  // 触发事件，仅传递最末级的选中ID
  emit("update-selection", { 
    id: lastSelectedId || "" // 如果没有选中任何项，则传递空字符串
  });
};







// const handleLevelClick = async (item: CategoryItem, level: number) => {
//   // 更新当前级别的选中ID
//   activeIds.value[level] = item.id;

//   // 清空更高级别的选中状态
//   for (let i = level + 1; i < 4; i++) {
//     activeIds.value[i] = "";
//   }

//   // 更新子级容器位置
//   if (level === 0) {
//     await nextTick();
//     updateSubLevelPosition();
//   }

//   // 获取当前选中节点的完整路径信息
//   const selectedNode = getSelectedNode(item, level);
  
//   // 触发事件，传递选中节点的完整信息
//   emit("update-selection", { 
//     ids: activeIds.value.filter(id => id),
//     node: selectedNode
//   });
// };
// 辅助函数：获取当前选中节点的完整信息
const getSelectedNode = (item: CategoryItem, level: number): CategoryItem | null => {
  if (!item) return null;

  // 克隆当前节点，避免直接修改原始数据
  const node = { ...item };

  // 递归获取子节点信息
  if (level < 3 && node.children) {
    node.children = node.children.map(child => {
      if (child.id === activeIds.value[level + 1]) {
        return getSelectedNode(child, level + 1);
      }
      return child;
    }).filter(Boolean) as CategoryItem[];
  }

  return node;
};

// 更新子级容器位置
const updateSubLevelPosition = () => {
  if (!activeIds.value[0] || level0Items.value.length === 0) return;
  
  const activeIndex = level0Data.value.findIndex(item => item.id === activeIds.value[0]);
  if (activeIndex === -1) return;
  
  const activeElement = level0Items.value[activeIndex];
  if (!activeElement) return;
  
  
  const rect = activeElement.getBoundingClientRect();
  const containerRect = filterContainer.value?.getBoundingClientRect();
  
  if (rect && containerRect) {
    subLevelPosition.value = {
      left: '0', // 靠左对齐
   top: `${rect.bottom - containerRect.top + 5}px`, // 显示在当前0级项的下方
      width: '100%' // 宽度与最外层同宽
    };
  }
};
// 点击空白处关闭子级窗口
const handleClickOutside = (event: MouseEvent) => {
  if (filterContainer.value && !filterContainer.value.contains(event.target as Node)) {
    activeIds.value = [];
  // emit("update-selection", { ids: [] });
  }
};

// 添加全局点击事件监听器
onMounted(() => {
  document.addEventListener('click', handleClickOutside);
  updateSubLevelPosition();
});

// 移除全局点击事件监听器
onUnmounted(() => {
  document.removeEventListener('click', handleClickOutside);
});
</script>

<style scoped>
.category-filter {
  width: 90%;
  position: relative;
}

/* 0级容器 - 横向排列，超出换行 */
.level-0-container {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  position: relative;
}

.level-0-item {
  padding: 4px 12px;
  border-radius: 16px;
  font-size: 13px;
  cursor: pointer;
  transition: all 0.2s;
  border: 1px solid #dcdfe6;
  color: #4e5969;
  white-space: nowrap;
  position: relative;
}

.level-0-item.active {
  background: #409eff;
  color: white;
  border-color: #409eff;
}

/* 1-3级容器 - 固定在当前选中的0级下方，靠左，宽度与最外层同宽 */
.sub-levels-container {
  position: absolute;
  z-index: 1000;
  padding: 15px;
  background: white;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

/* 各级样式 */
.level-1-container,
.level-2-container,
.level-3-container {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  margin-bottom: 10px;
}

.level-1-item,
.level-2-item,
.level-3-item {
  padding: 4px 12px;
  border-radius: 16px;
  font-size: 13px;
  cursor: pointer;
  transition: all 0.2s;
  border: 1px solid #dcdfe6;
  color: #4e5969;
  white-space: nowrap;
}

.level-1-item.active,
.level-2-item.active,
.level-3-item.active {
  background: #409eff;
  color: white;
  border-color: #409eff;
}

/* 层级缩进 */
.level-2-container {
  margin-top: 10px;
  padding: 10px;
  background: white;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  box-shadow: 0 2px 8px 0 rgba(0, 0, 0, 0.1);
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.level-3-container {
  margin-top: 10px;
  padding: 10px;
  background: white;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  box-shadow: 0 2px 8px 0 rgba(0, 0, 0, 0.1);
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}
</style>
